import { createNamespacedHelpers } from 'vuex'
import { computed } from 'vue'
import {
  useStore
} from './index'

/**
 * 实际遍历函数
 * @param mapper 遍历属性名
 * @param mapFn 被调用的辅助函数
 * @param type true => Mutations, Actions; false => States, Getters
 * @returns
 */
function mapStore(props: string[] | string, mapStoreFcn: Function, type: boolean = false){
  const propsList = mapStoreFcn(props)
  const store = useStore()
  const storeState = {} as any
  Object.keys(propsList).forEach(item => {
    const fn = propsList[item].bind({$store: store})
    // Mutations, Actions 为方法，返回函数体， States, Getters 为计算属性，返回非响应式数据
    storeState[item] = type ? fn : computed(fn).value
  })
  return storeState
}

/**
 * state辅助函数
 * @param moduleName 模块名
 * @param mapper 属性数组 或者 单属性 
 * @returns 
 */
export function useState(moduleName: string, props: string[] | string) {
  // 创建专属命名空间的store
  const store = createNamespacedHelpers(moduleName).mapState
  return mapStore(props, store)
}

/**
 * getters hook
 * @param moduleName 模块名
 * @param mapper 属性数组 或者 单属性
 * @returns 
 */
export function useGetters(moduleName: string, props: string[] | string){
  // 创建专属命名空间的store
  const store = createNamespacedHelpers(moduleName).mapGetters
  return mapStore(props, store)
}

export function useActions(moduleName: string, props: string[] | string){
  // 创建专属命名空间的store
  const store = createNamespacedHelpers(moduleName).mapActions
  return mapStore(props, store, true)
}

export function useMutations(moduleName: string, props: string[] | string){
  // 创建专属命名空间的store
  const store = createNamespacedHelpers(moduleName).mapMutations
  return mapStore(props, store, true)
}
